//
//  OrderDetailViewController.m
//  ATMCash
//
//  Created by zhengchengfeng on 2024/9/6.
//

#import "OrderDetailViewController.h"
#import "OrderDetModel.h"
#import "PreCollectionViewCell.h"

#import "IDVertifyViewController.h"
#import "PersonVertifyController.h"
#import "WorkInfoVertifyController.h"
#import "ContactVertifyController.h"
#import "BankVertifyController.h"

#import "IDVertifyModel.h"

#import "FaceViewController.h"
#import "IDVerfitySuccessController.h"


#define kCollCell  @"kCollCell"

#define kDefaultFixHeight (IS_IPhoneX_All ? kHeight_BottomSafe : 20)
 

@interface OrderDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic) UIView *headView;

@property (nonatomic) UILabel *maxLab,*priceLab,*loanLab,*rateLab;
@property (nonatomic) UIImageView *colBgView;

@property (nonatomic) UICollectionView *collectionView;
@property (nonatomic) NSMutableArray *listSource;

@property (nonatomic) OrderDetModel *model;

@property (nonatomic) BOOL isOffsetY;

@property (nonatomic) UIButton *returnBtn;

@end

@implementation OrderDetailViewController

- (void)loadCityData{
    [BaseDataEngine apiForPath:kCityAddressUrl method:kGetMethod parameter:nil onCompleteSuccess:^(NSDictionary *responseDic) {
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            return;
        }
        
        NSDictionary *dic = responseDic[@"recollecting"];
        NSArray *vanityAry = dic[@"vanity"];
        
        if (isArray(vanityAry)) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCityDataAry];
            
            [[NSUserDefaults standardUserDefaults] setValue:vanityAry forKey:kCityDataAry];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        
    } onCompleteFailur:^(NSError *error) {
        
    } withIsForm:NO];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    [self loadData];
}

- (void)back{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNeedRefreshOrderDetNotification object:nil];
    [super back];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Product Detail";
    self.view.backgroundColor = self.tableView.backgroundColor =  RGB(4, 44, 8);
    
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 48 - 20 - kDefaultFixHeight);
    
    [self initHeadView];
    
    [self.collectionView registerClass:[PreCollectionViewCell class] forCellWithReuseIdentifier:kCollCell];
    
    [self loadCityData];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kNeedRefreshOrderDetNotification object:nil];
    
}

- (void)loadData{
    NSMutableDictionary *muDic = @{
        @"gardens":esString(self.orderIdStr),
        @"tuesday":@"tuesdayOrderDet",
        @"needn":@"neednOrderDet",
    }.mutableCopy;
    [BaseDataEngine apiForPath:kProductDetUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        DLog(@"=====%@",responseDic);
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        
        [self.data removeAllObjects];
       
        
        NSDictionary *dic = responseDic[@"recollecting"];
       
        OrderDetModel *model = [OrderDetModel mj_objectWithKeyValues:dic];
        self.model = model;
        
        self.listSource = [BonedModel mj_objectArrayWithKeyValuesArray:model.boned];
        [self initHeadDataView];
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:kOrderNumber];
        [[NSUserDefaults standardUserDefaults] setValue:esString(self.model.lonesome.smaller) forKey:kOrderNumber];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
    } withIsForm:YES];
    
}

- (void)initHeadView{
    UIImage *iconImg = [UIImage imageNamed:@"icon_orderDetBgV"];
    UIImage *colImg = [UIImage imageNamed:@"icon_order1"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,DimensionBaseIphone6(406) + DimensionBaseIphone6(colImg.size.height + 20))];
    headView.backgroundColor = [UIColor clearColor];
    headView.userInteractionEnabled = YES;
    self.tableView.tableHeaderView = headView;
    self.headView = headView;
    
    UIButton *returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, DimensionBaseIphone6(44), 44, DimensionBaseIphone6(44))];
    [returnBtn setImage:[UIImage imageNamed:@"icon_returnWhite"] forState:UIControlStateNormal];
    [returnBtn setImage:[UIImage imageNamed:@"icon_returnWhite"] forState:UIControlStateHighlighted];
    [returnBtn setImage:[UIImage imageNamed:@"icon_returnWhite"] forState:UIControlStateSelected];
    [returnBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:returnBtn];
    self.returnBtn = returnBtn;
}

- (void)initHeadDataView{
    
    UIImage *iconImg = [UIImage imageNamed:@"icon_orderDetBgV"];
    UIImage *colImg = [UIImage imageNamed:@"icon_order1"];
    UIImageView *iconBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(406))];
    [self.headView addSubview:iconBg];
    iconBg.image = iconImg;
    
    if (self.returnBtn) {
        [self.returnBtn removeFromSuperview];
    } 
    [self.headView addSubview:self.returnBtn];
    
    UILabel *titleLab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:16] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    titleLab.frame = CGRectMake(0, DimensionBaseIphone6(44), kScreenWidth, DimensionBaseIphone6(44));
    [self.headView addSubview:titleLab];
    titleLab.textAlignment = 1;
    
    UIImage *mdImg = [UIImage imageNamed:@"icon_order2"];

    UIImageView *mdImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, DimensionBaseIphone6(105), kScreenWidth - 30, DimensionBaseIphone6(260))];
    mdImgView.image = mdImg;
    [self.headView addSubview:mdImgView];
    
    self.maxLab = [Utility createLabel:[UIFont fontWithName:kFuturaBold size:12] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    self.maxLab.frame = CGRectMake(0, DimensionBaseIphone6(90), mdImgView.size.width, DimensionBaseIphone6(20));
    self.maxLab.textAlignment = 1;
    [mdImgView addSubview:self.maxLab];
    
    self.priceLab = [Utility createLabel:[UIFont fontWithName:kFuturaBold size:38] color:[UIColor colorWithHexString:@"#FFEFC0"]];
    self.priceLab.frame = CGRectMake(0, self.maxLab.bottom + DimensionBaseIphone6(20), mdImgView.size.width, DimensionBaseIphone6(44));
    [mdImgView addSubview:self.priceLab];
    self.priceLab.textAlignment = 1;
    
    self.loanLab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:13] color:[UIColor colorWithHexString:@"#D9E4CE"]];
    [mdImgView addSubview:self.loanLab];
    self.loanLab.frame = CGRectMake(0, self.priceLab.bottom + DimensionBaseIphone6(15), mdImgView.size.width/2, DimensionBaseIphone6(45));
    
    self.loanLab.textAlignment = 1;
    self.loanLab.numberOfLines = 2;
    
    self.rateLab = [Utility createLabel:[UIFont fontWithName:kFuturaMedium size:13] color:[UIColor colorWithHexString:@"#D9E4CE"]];
    [mdImgView addSubview:self.rateLab];
    self.rateLab.frame = CGRectMake(self.loanLab.right, self.loanLab.top, mdImgView.size.width/2, DimensionBaseIphone6(50));
    self.rateLab.textAlignment = 1;
    self.rateLab.numberOfLines = 2;
    
    
    titleLab.text = esString(self.model.lonesome.harness);
    self.maxLab.text = @"Maximum Amount";
    self.priceLab.text = [NSString stringWithFormat:@"%@",esString(self.model.lonesome.candle)];//₱
    self.loanLab.text = [NSString stringWithFormat:@"%@\n%@ days",@"Loan Term",esString(self.model.lonesome.wilderness)];
    self.rateLab.text = [NSString stringWithFormat:@"%@\n%@ days",@"Interest Rate",esString(self.model.lonesome.aside.regal.villages)];

    [self.loanLab addAttributesArray:@[@{NSFontAttributeName:[UIFont fontWithName:kFuturaMedium size:18]},@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFEFC0"]}] forStringArray:@[esString(self.model.lonesome.wilderness),esString(self.model.lonesome.wilderness)]];
    
    [self.rateLab addAttributesArray:@[@{NSFontAttributeName:[UIFont fontWithName:kFuturaMedium size:18]}] forStringArray:@[esString(self.model.lonesome.aside.regal.villages)]];
    
    UIImageView *colBgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, iconBg.bottom + DimensionBaseIphone6(20), kScreenWidth - 40, DimensionBaseIphone6(colImg.size.height))];
    self.colBgView.userInteractionEnabled = YES;
    colBgView.image = colImg;
    [self.headView addSubview:colBgView];
    self.colBgView = colBgView;
    
    [self createCollectScrollView];
    
    UILabel *tipsLab = [Utility createLabel:[UIFont fontWithName:kFutura size:10] color:RGB(241, 243, 242)];
    tipsLab.text = @"*It is used for real-name identity verification, anti-money laundering and quota assessment. The data will be encrypted and protected.";
    tipsLab.textAlignment = 1;
    tipsLab.numberOfLines = 2;
    [colBgView addSubview:tipsLab];
    tipsLab.frame = CGRectMake(15, colBgView.size.height - DimensionBaseIphone6(15) - DimensionBaseIphone6(30), colBgView.size.width - 30, DimensionBaseIphone6(30));
    
    
    
    
    
    
    
    UIButton *footBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, kScreenHeight - 48 - kDefaultFixHeight, kScreenWidth - 40, 48)];
    [footBtn setTitle:esString(self.model.lonesome.fierce) forState:UIControlStateNormal];
    [footBtn setTitle:esString(self.model.lonesome.fierce) forState:UIControlStateSelected];
    [footBtn setTitle:esString(self.model.lonesome.fierce) forState:UIControlStateHighlighted];
    [footBtn setBackgroundImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateNormal];
    [footBtn setBackgroundImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateSelected];
    [footBtn setBackgroundImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateHighlighted];
    [footBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
    [footBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateSelected];
    [footBtn setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateHighlighted];
    [self.view addSubview:footBtn];
    footBtn.titleLabel.font = [UIFont fontWithName:kFuturaBold size:15];
    
    [footBtn addTarget:self action:@selector(clickStartBorrowing) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

#pragma mark ---UICollectionView
- (void)createCollectScrollView{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.colBgView.left, DimensionBaseIphone6(50) + self.colBgView.top, self.colBgView.size.width, self.colBgView.size.height - DimensionBaseIphone6(50) - DimensionBaseIphone6(45)) collectionViewLayout:flowLayout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[PreCollectionViewCell class] forCellWithReuseIdentifier:kCollCell];
    
    [self.headView addSubview:self.collectionView];
    
    [self.collectionView reloadData];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.listSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollCell forIndexPath:indexPath];
    
    cell.model = self.listSource[indexPath.item];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
   return CGSizeMake(DimensionBaseIphone6(15+120), DimensionBaseIphone6(15 + 120 + 30));
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PreCollectionViewCell *selCell = (PreCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    BonedModel *mm = selCell.model;
    DLog(@"...... %@",mm.ego);
    
    if ([mm.tumbled isEqualToString:kMakemoneyf]) {
        [self goIdentifyVertify];
    }
    else if ([mm.tumbled isEqualToString:kMakemoneyg]) {
        if ([mm.teetotallers integerValue] == 1) {
            [self goPersonalVertify];
        } else {
            [self clickStartBorrowing];
        }
        
    }
    else if ([mm.tumbled isEqualToString:kMakemoneyh]) {
        if ([mm.teetotallers integerValue] == 1) {
            [self goWorkVertify];
        } else {
            [self clickStartBorrowing];
        }
    }
    else if ([mm.tumbled isEqualToString:kMakemoneyi]) {
        if ([mm.teetotallers integerValue] == 1) {
            [self goContactVertify];
        } else {
            [self clickStartBorrowing];
        }
    }
    else if ([mm.tumbled isEqualToString:kMakemoneyj]) {
        if ([mm.teetotallers integerValue] == 1) {
            [self goBankVertify];
        } else {
            [self clickStartBorrowing];
        }
    }

    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark ----identifyVertify
- (void)goIdentifyVertify{
    [CreaditUtilsHelper boxShowLoadWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"gardens":esString(self.orderIdStr),
        @"loose":@"looseIdentify"
    }.mutableCopy;
    [BaseDataEngine apiForPath:kIDCardVertifyUrl method:kGetMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }

        NSDictionary *dic = responseDic[@"recollecting"];
        
        IDVertifyModel *model = [IDVertifyModel mj_objectWithKeyValues:dic];
        
       
        if ([model.spluttering.teetotallers integerValue] == 0) {
            IDVertifyViewController *vc = [[IDVertifyViewController alloc] init];
            vc.ocrCardArr = model.wherever;
            vc.idStr = esString(self.orderIdStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
      
        else if ([model.spluttering.teetotallers integerValue] == 1 && [model.abruptly integerValue] == 0 ){
            FaceViewController *vc = [[FaceViewController alloc] init];
            vc.cardStr = esString(model.spluttering.giggling);
            vc.idStr = esString(self.orderIdStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if ([model.spluttering.teetotallers integerValue] == 1 && [model.abruptly integerValue] == 1){
            IDVerfitySuccessController *vc = [[IDVerfitySuccessController alloc] init];
            vc.cardStr = esString(model.spluttering.giggling);
            vc.nameStr = esString(model.spluttering.smoke.cambridge);
            vc.idNoStr = esString(model.spluttering.smoke.swallowed);
            vc.birDateStr = esString(model.spluttering.smoke.tightening);
            vc.idStr = esString(self.orderIdStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:NO];

}

#pragma mark ----personalVertify
- (void)goPersonalVertify{
    PersonVertifyController *vc = [[PersonVertifyController alloc] init];
    vc.idStr = esString(self.orderIdStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----workVertify
- (void)goWorkVertify{
    WorkInfoVertifyController *vc = [[WorkInfoVertifyController alloc] init];
    vc.idStr = esString(self.orderIdStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----contactVertify
- (void)goContactVertify{
    ContactVertifyController *vc = [[ContactVertifyController alloc] init];
    vc.idStr = esString(self.orderIdStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----bankVertify
- (void)goBankVertify{
    BankVertifyController *vc = [[BankVertifyController alloc] init];
    vc.idStr = esString(self.orderIdStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ---StartBorrowing
- (void)clickStartBorrowing{
    if (PMObjectIsEmpty(self.model.laughing)) {
        NSString *stTime = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        NSMutableDictionary *muDic = @{
            @"commissariat":esString(self.model.lonesome.smaller),
            @"tracked":@"trackedIdStr",
            @"rot":@"rotIdStr",
            @"thrown":@"thrownIdStr",
            @"object":@"objectIdStr",
        }.mutableCopy;
        [CreaditUtilsHelper boxShowLoadWithMessage:@""];
        [BaseDataEngine apiForPath:kByOrderIdGetUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
            [CreaditUtilsHelper hideLoadMessageBox];
            if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
                return;
            }
            [CreditServerHelper uploadMaiDianDataStartTimeStr:stTime andEndTimeStr:[NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"] withTypeStr:@"9" withFirmly:esString(self.orderIdStr) withSmaller:esString(self.model.lonesome.smaller)];
            
            NSDictionary *dic = responseDic[@"recollecting"];
            
            [[CreditCore globleCore] jumpToPage:esString(dic[@"exulting"])];
            
        } onCompleteFailur:^(NSError *error) {
            [CreaditUtilsHelper hideLoadMessageBox];
        } withIsForm:YES];
        
        return;
        
    }
    
   
    
    
    if ([self.model.laughing.tumbled isEqualToString:kMakemoneyf]) {
        [self goIdentifyVertify];
    }
    else if ([self.model.laughing.tumbled isEqualToString:kMakemoneyg]) {
        [self goPersonalVertify];
    }
    else if ([self.model.laughing.tumbled isEqualToString:kMakemoneyh]) {
        [self goWorkVertify];
    }
    else if ([self.model.laughing.tumbled isEqualToString:kMakemoneyi]) {
        [self goContactVertify];
    }
    else if ([self.model.laughing.tumbled isEqualToString:kMakemoneyj]) {
        [self goBankVertify];
    }
    
    
    
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat offset_Y = scrollView.contentOffset.y;
   
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }
    else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:0];
            [self loadData];
        }
    }
}

@end
